// Copyright (C) 2009 Taylor L. Riche <riche@cs.utexas.edu>
//  
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software 
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// $Id: NetDevice.hh 1112 2009-09-15 21:56:48Z djwhitebread $
//

#ifndef _NETDEVICE_HH_
#define _NETDEVICE_HH_

#include <assert.h>
#include <pthread.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>

#include <netinet/in.h>

#include <errno.h>

#include <iostream>

#include <boost/shared_ptr.hpp>

#include <lagniappe/RequestDevice.h>
#include <lagniappe/RCon.h>
#include <lagniappe/RData.h>

#include <sysmodel/Synchronized.hh>

#include "../messages/AddrBytes.hpp"
#include "../membership/Membership.hpp"
#include "../util/Role.hpp"
#include "../cmdline.h"

#include "BaseNode.hpp"
#include "TCPNetwork.hpp"

typedef uint16_t socket_t;


#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

  void * startNetDeviceClient(void * arg);
  void * startNetDeviceOrder(void * arg);
  void * startNetDeviceExec(void * arg);

#ifdef __cplusplus
}
#endif /* __cplusplus */
namespace requestDevices {

  const std::string FILENAME = "bft.properties";
  template <BFT::util::Role R>
  class NetDevice : public lagniappe::RequestDevice, Synchronized
  {
    pthread_t coreThread;
    boost::shared_ptr<BFT::BaseNode> bn;
    boost::shared_ptr<BFT::network::TCPNetwork> tcpN;
    BFT::util::Role myRole;
    gengetopt_args_info * args;
    bool ready;
  public:
    NetDevice(std::string intf, void *);
    ~NetDevice();
    void process();
    virtual void run(lagniappe::RCon * rcon);
    virtual void start();
  };



  //int NetDevice::procNum = 10;

  template <BFT::util::Role R>
  NetDevice<R>::NetDevice(std::string intf, void * arg_struct) : ready(false)
  {
    if(arg_struct != NULL) args = (gengetopt_args_info *)arg_struct;
    int index = args->replica_id_arg;
    destVec.resize(4);
    boost::shared_ptr<BFT::membership::Membership> _mem(new BFT::membership::Membership(FILENAME, BFT::util::ORDER, index));
    boost::shared_ptr<BFT::BaseNode> _bn(new BFT::BaseNode(BFT::util::ORDER, _mem));
    bn = _bn;
    boost::shared_ptr<BFT::network::TCPNetwork> _tcp(new BFT::network::TCPNetwork(R, _mem));
    tcpN = _tcp;
    myRole = R;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    if(myRole == BFT::util::CLIENT) {
      if(pthread_create(&coreThread, &attr, startNetDeviceClient, (void*) this)) {
	std::cerr << "pthread_create failed" << strerror(errno) << std::endl;
	std::exit(1);
      }
    }
    else if(myRole == BFT::util::ORDER) {
      if(pthread_create(&coreThread, &attr, startNetDeviceOrder, (void*) this)) {
	std::cerr << "pthread_create failed" << strerror(errno) << std::endl;
	std::exit(1);
      }
    }
    else if(myRole == BFT::util::EXEC) {
      if(pthread_create(&coreThread, &attr, startNetDeviceExec, (void*) this)) {
	std::cerr << "pthread_create failed" << strerror(errno) << std::endl;
	std::exit(1);
      }
    }
  }

  template<BFT::util::Role R>
  NetDevice<R>::~NetDevice() 
  {
    if(tcpN != NULL) 
      tcpN->stop();
  }

  template<BFT::util::Role R>
  void 
  NetDevice<R>::process() 
  {
    Synchronized::Scope mutex(this);
    while(!ready) {
	wait();
    }
    while(true) {
      std::pair<lagniappe::CoreOp *, uint32_t> * dest = destVec.at(3);
      if(dest != NULL && dest->first != NULL) {
	std::vector< boost::tuple< int , boost::shared_ptr<char> , int > > vec = tcpN->selectMessages();
	for(std::vector< boost::tuple< int , boost::shared_ptr<char> , int > >::iterator iter = vec.begin(); iter != vec.end(); iter++) {
	  BFT::messages::AddrBytes * tempAB = new BFT::messages::AddrBytes((*iter).get<1>(), (*iter).get<2>(), (*iter).get<0>());
	  lagniappe::RCon * newRCon = new lagniappe::RCon(dest->first, static_cast<lagniappe::RData *>(tempAB), dest->second, sizeof(tempAB));
	  //std::cerr << "got msg: " << newRCon->getPort() << std::endl;
	  dest->first->run(newRCon);
	}
      }
    }
    return;
  }

  template<BFT::util::Role R>
  void 
  NetDevice<R>::run(lagniappe::RCon * rcon)
  {
    boost::shared_ptr<BFT::messages::AddrBytes> msg(static_cast<BFT::messages::AddrBytes *>(rcon->getRData()));
    if(myRole == BFT::util::CLIENT) {
      if(msg->getIndex() == BFT::messages::ALL_REPLICAS) {
	bn->sendToAllClients(msg->getBuffer(), msg->getBL());
      }
      else {
	bn->sendToClient(msg->getBuffer(), msg->getBL(), msg->getIndex());
      }
    }
    else if(myRole == BFT::util::EXEC) {
      if(msg->getIndex() == BFT::messages::ALL_REPLICAS) {
	bn->sendToAllExec(msg->getBuffer(), msg->getBL());
      }
      else {
	bn->sendToExec(msg->getBuffer(), msg->getBL(), msg->getIndex());
      }
    }
    else if(myRole == BFT::util::ORDER) {
      if(msg->getIndex() == BFT::messages::ALL_REPLICAS) {
	bn->sendToAllOrder(msg->getBuffer(), msg->getBL());
      }
      else {
	bn->sendToOrder(msg->getBuffer(), msg->getBL(), msg->getIndex());
      }
    }

  }

  template<BFT::util::Role R>
  void 
  NetDevice<R>::start()
  {
    Synchronized::Scope mutex(this);
    tcpN->start();
    ready = true;
    notifyAll();
  }

}

#endif // _CLIENTS_HH_
